/*
 * Copyright ©2017 贾维程. All rights reserved.
 */

package org.handover.controller.admin.user;

import org.handover.Tools.Tools;
import org.handover.domain.Role;
import org.handover.domain.User;
import org.handover.domain.UserGroup;
import org.handover.repository.RoleRepository;
import org.handover.repository.UserGroupRepository;
import org.handover.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/admin/user/")
public class UserController {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserGroupRepository userGroupRepository;
    @Autowired
    private RoleRepository roleRepository;

    @GetMapping("list")
    public String list(Model model) {
        if (Tools.hasRole("root")) {
            System.out.println("has root");
            System.out.println(userRepository.findByRoleSet_RoleNotIn(new ArrayList<>(Arrays.asList("root", "admin"))));
        }
        //UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //for (SimpleGrantedAuthority simpleGrantedAuthority:userDetails.getAuthorities())
        model.addAttribute("userList",userRepository.findAll());
        return "admin/user/list";
    }

    @GetMapping("edit")
    public String toAdd(Model model) {
        model.addAttribute(new User());
        //model.addAttribute("userGroupList", userGroupList());
        return "admin/user/edit";
    }

    @GetMapping("edit/{id}")
    public String toEdit(@PathVariable Long id, Model model) {
        model.addAttribute("user",userRepository.getOne(id));
        //model.addAttribute("userGroupList", userGroupList());
        return "admin/user/edit";
    }

    @PostMapping("edit")
    @Transactional
    public String edit(@Validated User user, BindingResult bindingResult, RedirectAttributes model) {
        if (bindingResult.hasErrors()) {
            //model.addAttribute("userGroupList", userGroupList());
            return "admin/user/edit";
        }
        if (!usernameValidate(user.getId(), user.getUsername())){
            //model.addAttribute("userGroupList", userGroupList());
            bindingResult.rejectValue("username", "user.username.exist", "账号已存在");
            return "admin/user/edit";
        }
        if (null == user.getId()){
            PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
            String encode = passwordEncoder.encode(user.getUsername());
            user.setPassword(encode);
            userRepository.save(user);
        } else {
            userRepository.updateUser(user.getUsername(),user.getEnable(),user.getUserGroup(),user);
        }

        model.addFlashAttribute("message","保存成功");
        return "redirect:/admin/user/list";
    }

    @GetMapping("delete/{id}")
    @Transactional
    public String delete(@PathVariable Long id, RedirectAttributes model) {
        User user = userRepository.getOne(id);
        if (user.getHandoverList().isEmpty()) {
            userRepository.deleteById(id);
            model.addFlashAttribute("message","删除成功");
        } else{
            model.addFlashAttribute("message","此员工有交接内容不允许删除");
        }
        return "redirect:/admin/user/list";
    }

    @GetMapping("usernameValidate")
    @ResponseBody
    public boolean usernameValidate(Long id, String username) {
        return null == id ? !userRepository.existsByUsername(username) : !userRepository.existsByIdNotAndUsername(id, username);
    }

    @ModelAttribute(value = "userGroupList")
    public List<UserGroup> userGroupList(){
        return userGroupRepository.findAll(Sort.by(Sort.Direction.ASC,"no"));
    }
}
